<template>
  <!-- {{title}}批次详情 -->
  <div class="main_page {{name}}-detail">
    <back-header title="{{title}}-查看详情" class="flex_0"></back-header>
    <div class="filters-wrap">
      <tool-bar defaultOpen>
        <template v-slot:main>
          <!-- 输入类型筛选 -->
          <tool-bar-item label="">
            <el-input v-model="planData." size="mini" placeholder="" clearable></el-input>
          </tool-bar-item>
          <!-- 远程选择类型筛选 -->
          <tool-bar-item label="">
            <el-select
              v-model="planData."
              filterable
              remote
              reserve-keyword
              clearable
              placeholder=""
              size="mini"
              :remote-method="searchOperator"
              :loading="searchOperatorLoading">
              <el-option v-for="i in operatorList" :key="i." :label="i." :value="i."></el-option>
            </el-select>
          </tool-bar-item>
          <!-- 静态选择类型筛选 -->
          <tool-bar-item label="">
            <el-select v-model="planData.approveStatus" placeholder="" size="mini">
              <el-option :label="item." :value="item." v-for="item in " :key="item."></el-option>
            </el-select>
          </tool-bar-item>
        </template>
        <template v-slot:btn>
          <el-button @click.stop="searchClick()" type="primary" size="mini">搜索</el-button>
          <el-button @click.stop="resetClick()" size="mini">重置</el-button>
        </template>
      </tool-bar>
    </div>
    <!-- 操作 -->
    <section class="funcBar mt20 full-w">
      <div class="table-total">
        <div>
          <span>总笔数：</span>
          <span class="total-num">{{ allNum }}</span>
        </div>
        <div>
          <span>执行成功：</span>
          <span class="total-num">{{ successNum }}</span>
        </div>
        <div>
          <span>执行失败：</span>
          <span class="total-num">{{ failNum }}</span>
        </div>
      </div>
      <div class="button-groups">
        <el-button size="small" type="primary" :disabled="!totalNum" @click="allOperationClick">
          全部执行
        </el-button>
        <el-button size="small" class="ml20" type="default" :disabled="batchInfo.allNum === 0" @click="exportTable">导出</el-button>
      </div>
    </section>

    <div class="main_count" v-loading="tableLoading">
      <ApiTable
        height="100%"
        :tableData="tableData"
        :tableProp="tableProp"
        fixedOperate="right"
        showOperate
        operateWidth="150">
        <template v-slot:table-operate="{ content }">
          <el-button type="text" size="small" @click="openEdit(content)">修改</el-button>
          <el-button type="text" size="small" @click="singleOperation(content)">重新审批</el-button>
          <el-button type="text" size="small" @click="singleDel(content)">删除</el-button>
        </template>
      </ApiTable>
    </div>

    <!-- 分页组件 -->
    <pagination :pageNo="pageData.pageNo" :pageSize="pageData.pageSize" :total="totalNum" @paginationChange="paginationChange"></pagination>

    <!-- 修改单条数据 -->
    <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="550px" center top="15%">
      <el-form ref="editForm" :model="singleInfo" label-width="127px" :rules="editRules()">
        <el-form-item v-show="item.show ? item.show(singleInfo) : true" :label="item.title" v-for="item in editFields" :key="item.key" :prop="item.key">
          <!-- 文本输入框 -->
          <el-input
            v-if="!item.select"
            v-model="singleInfo[item.key]"
            :placeholder="`请输入${item.title}`"
            :maxlength="item.maxLength"
            @input="item.input(singleInfo)"
            @change="item.change || false"
            size="mini"
            clearable>
          </el-input>
          <!-- select选择器 -->
          <el-select v-else v-model="singleInfo[item.key]" :placeholder="`请选择${item.title}`" size="mini" @change="item.change || false">
            <el-option :label="sel.name" :value="sel.id" v-for="sel in item.dataList" :key="sel.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
        <el-button size="mini" type="primary" @click="sureEdit">确定</el-button>
        <el-button size="mini" @click="editDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ToolBar, ToolBarItem, BackHeader, Pagination, ApiTable } from '@/components'
import {
  。批次详情列表接口。, // 批次详情列表接口
  。批次统计信息接口。, // 批次统计信息接口（总笔数/成功数/失败数）
  。全部执行操作接口。, // 全部执行操作接口
  。导出列表接口。, // 导出列表接口
  。操作人列表接口。, // 获取操作人列表接口
  。修改单条数据详情信息接口。, // 修改单条数据详情信息接口
  。删除单条数据接口。, // 删除单条数据接口
  。重新操作接口。 // 重新操作接口
} from '@/services'
import {
  batchDetailTableProps, // 批次详情列表键值表[ { key: 'key', value: 'value' } ]
  batchDetailStatusList, // 批次详情执行状态枚举
  。单条数据数据状态枚举。, // 单条数据数据状态枚举
  batchDetailEditFields // 批量修改字段表
} from '../tmps/props'
export default {
  components: { ToolBar, ToolBarItem, BackHeader, ApiTable, Pagination },
  data () {
    return {
      tableProp: batchDetailTableProps,
      batchId: null,
      // 预备搜索参数
      planData: {},
      // 分页参数
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      // 筛选项
      postData: {},
      optUser: null,
      searchOperatorLoading: false,
      operatorList: [],
      tableLoading: false,
      tableData: [],
      totalNum: 0,
      batchInfo: {},
      // 修改信息
      editDialogVisible: false,
      singleInfo: {},
      editFields: batchDetailEditFields,
      // 删除信息
      delList: []
    }
  },
  computed: {
    statusList () {
      return [ { id: null, name: '全部' }, ...batchDetailStatusList ]
    },
    approvalStatusList () {
      return [ { id: null, name: '全部' }, ...approvalStatusList ]
    },
    allNum () {
      let { allCount = 0 } = this.batchInfo || {}
      return allCount || '--'
    },
    successNum () {
      let { successCount = 0 } = this.batchInfo || {}
      return successCount || '--'
    },
    failNum () {
      let { errorCount = 0 } = this.batchInfo || {}
      return errorCount || '--'
    }
  },
  created () {
    this.batchId = this.$route.params.batchId
    this.resetClick()
  },
  methods: {
    /**
     * 获取批次详情列表
     * @author chaiyf
     * @date {{dateTime}}
     */
    getList () {
      let postData = {
        batchId: this.batchId,
        ...this.postData,
        ...this.pageData
      }
      this.tableLoading = true
      。批次详情列表接口。(postData).then(({ result, data, msg }) => {
        if (result === 1) {
          let { records = [], total = 0 } = data
          this.tableData = records
          this.tableData.forEach((e, index) => {
            let exeStatusObj = this.statusList.find(item => item.id === Number(e.exeStatus)) || {}
            let approveStatusObj = this.approvalStatusList.find(item => item.id === Number(e.approveStatus)) || {}
            e.exeStatusStr = exeStatusObj.name || ''
            e.approveStatusStr = approveStatusObj.name || ''
            e.approveResult = Number(e.approveResult) === 1 ? '不通过' : (Number(e.approveResult) === 0 ? '通过' : '')
          })
          this.totalNum = total
        } else {
          this.$message.error(msg || data)
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    /**
     * 获取批次详情统计信息
     * @author chaiyf
     * @date {{dateTime}}
     */
    getInfo () {
      。批次统计信息接口。({ batchId: this.batchId }).then(({ result, data, msg }) => {
        if (result === 1) {
          this.batchInfo = { ...data }
        } else {
          this.$message.error(msg || data)
        }
      })
    },
    /**
     * 动态搜索流程发起人列表
     * @author chaiyf
     * @date {{dateTime}}
     * @param {string} query 模糊搜索输入的文本
     */
    searchOperator (query = '') {
      if (query !== '') {
        this.searchOperatorLoading = true
        。操作人列表接口。({ name: query }).then(({ result, data = [], msg }) => {
          if (result === 1) {
            this.operatorList = data
          } else {
            this.$message.error(msg || data)
          }
        }).finally(() => {
          this.searchOperatorLoading = false
        })
      }
    },
    /**
     * 分页数据变化的时候触发请求
     * @author chaiyf
     * @date {{dateTime}}
     * @param {object} {} 分页数据变化的时候返回的分页数据
     * @param {string|number} pageNo - 分页页数
     * @param {string|number} pageSize - 每页数据量
     */
    paginationChange ({ pageNo, pageSize }) {
      this.pageData.pageNo = pageNo
      this.pageData.pageSize = pageSize
      this.getList()
    },
    /**
     * 筛选栏搜索
     * @author chaiyf
     * @date {{dateTime}}
     */
    searchClick () {
      this.pageData.pageNo = 1
      this.postData = {
        ...this.planData
      }
      this.getList()
    },
    /**
     * 筛选栏重置
     * @author chaiyf
     * @date {{dateTime}}
     */
    resetClick () {
      this.addTime = null
      this.optUser = null
      this.pageData.pageNo = 1
      this.postData = this.planData = {
        procCode: null,
        exeStatus: null,
        approveStatus: null,
        status: null,
        startUserId: null
      }
      this.getInfo()
      this.getList()
    },
    /**
     * 全部操作
     * @author chaiyf
     * @date {{dateTime}}
     */
    allOperationClick () {
      this.$confirm('确定全部执行该批次流程', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        。全部执行接口。({ batchId: this.batchId }).then(({ result, data, msg }) => {
          if (result === 1) {
            this.$message.success('操作成功')
            this.resetClick()
          } else {
            this.$message.error(msg || data)
          }
        })
      })
    },
    /**
     * 导出操作
     * @author chaiyf
     * @date {{dateTime}}
     */
    exportTable () {
      。导出接口。({ batchId: this.batchId, ...this.postData }).then(({ result, data, msg }) => {
        if (result === 1) {
          this.$message.success('发起导出申请成功，请稍后到工具箱中的下载中心查看')
        } else {
          this.$message.error(msg || data || '导出失败')
        }
      })
    },
    /**
     * 修改单条数据
     * @author chaiyf
     * @date {{dateTime}}
     * @param {object} 修改的数据信息
     */
    openEdit ({ 。修改数据参数。 }) {
      this.singleInfo = { 。修改数据参数。 }
      this.editDialogVisible = true
    },
    /**
     * 修改规则
     * @author chaiyf
     * @date {{dateTime}}
     * @returns {array}
     */
    editRules () {
      let requiredFields = this.editFields.filter(item => { return item.required })
      let rules = {}
      for (let a = 0; a < requiredFields.length; a++) {
        let item = requiredFields[a]
        rules[item.key] = [
          { required: true, message: `${item.title}不能为空`, trigger: 'blur' }
        ]
      }
      return rules
    },
    /**
     * 确认修改
     * @author chaiyf
     * @date {{dateTime}}
     */
    sureEdit () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          delete this.singleInfo.procDefCode
          delete this.singleInfo.label
          。确认修改接口。(this.singleInfo).then(({ result, data, msg }) => {
            if (result === 1) {
              this.$message.success('修改成功')
              this.editDialogVisible = false
              this.resetClick()
            } else {
              this.$message.error(msg || data || '修改失败')
            }
          })
        }
      })
    },
    /**
     * 单条删除
     * @author chaiyf
     * @date {{dateTime}}
     * @param {object} 需要单条删除的数据
     */
    singleDel ({ id }) {
      this.delConfirm([id])
    },
    /**
     * 删除操作
     * @author chaiyf
     * @date {{dateTime}}
     */
    delConfirm (detailIds = []) {
      if (!detailIds.length) { return false }
      detailIds = [...detailIds].join(',')
      const content = detailIds.length > 1 ? `您选择了${detailIds.length}条数据，确定批量删除？` : '确定删除该条数据？'
      this.$confirm(content, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        。删除接口。({ detailIds }).then(({ result, data, msg }) => {
          if (result === 1) {
            this.$message.success('删除成功')
            this.resetClick()
          } else {
            this.$message.error(msg || data || '删除失败')
          }
        })
      })
    },
    /**
     * 重新操作
     * @author chaiyf
     * @date {{dateTime}}
     * @param {object} 需要重新操作的数据
     */
    singleOperation ({ id }) {
      this.$confirm('确定重新审批该流程', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        。重新操作接口。({ detailId: id }).then(({ result, data, msg }) => {
          if (result === 1) {
            this.$message.success('操作成功')
            this.resetClick()
          } else {
            this.$message.error(msg || data || '操作失败')
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
@import '@/assets/styles/mixin.scss';
.batch-approval-detail {
  padding-top: 0;

  .filters-wrap {
    box-sizing: border-box;
    width: 100%;
  }

  .funcBar {
    @extend .flexRowSpbCen;
    width: 100%;
    .table-total {
      @extend .flexRowStarCen;
      &>div {
        margin-right: 30px;
      }
    }
  }
  .mt20 { margin-top: 20px; }
  .ml20 { margin-left: 20px; }

  .procDefNameBox {
    @extend .flexRowStarCen;
    &>span:nth-child(1) {
      margin-right: 10px;
    }
  }
}
</style>
